import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import moment from 'moment'
import style from './Statistic.module.less'
import AcceptStatistic from '@components/CaseStatistic/AcceptStatistic'
// import FinanceStatistic from '@components/CaseStatistic/FinanceStatistic'
import ForeignStatistic from '@components/CaseStatistic/ForeignStatistic'
// import OtherPlaceStatistic from '@components/CaseStatistic/OtherPlaceStatistic'
import ClosureStatistic from '@components/CaseStatistic/ClosureStatistic'
import ProcedureStatistic from '@components/CaseStatistic/ProcedureStatistic'
import AcceptTypeStatistic from '@components/CaseStatistic/AcceptTypeStatistic'
import { Button, message, Modal } from 'antd'
import { DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { json2Excel } from '@js/excel'
// import CaseTypeStatistic from '@components/CaseStatistic/CaseTypeStatistic'
import SearchForm from '@components/SearchForm/Index'
const { confirm } = Modal
const params = ['party_area_tag', 'type', 'beginTime', 'endTime', 'cause_action', 'cause_use_type', 'closure_type', 'minDisputeAmount', 'maxDisputeAmount', 'procedure', 'causeactionType', 'party_address']
class CaseStatistic extends Component {
  state = {
    disputeamount: 0,
    casenum: 0,
    isLoading: false,
    isLoadError: false,
    dictionaries: {},
    formData: {},
    condition: JSON.stringify([]),
    searchVersion: Date.now(),
    chartOneData: {},
    chartTwoData: {},
    chartThreeData: {},
    chartFourData: {},
    chartFiveData: {},
    chartSixData: {},
    chartSevenData: {},
    type: 'accept_datetime'
  }

  formRef = React.createRef()

  initData () {
    const formData = this.props.meta.formData || {}
    const c = this.formRef.current
    c.showAll()
    setTimeout(() => {
      c.setFieldsValue(formData)
      c.submit()
    }, 0)
  }

  // 转换单位
  transferUnit (v) {
    if (v > 100000000) {
      return Math.round(v / 1000000) / 100 + ' 亿'
    }
    if (v > 10000) {
      return Math.round(v / 100) / 100 + ' 万'
    }
    return v
  }

  // 获取全部数据统计
  getTotalStatistic () {
    this.setState({ isLoading: true, isLoadError: false })
    this.$get('/api/xapc/casestat/statSumData', {
      condition: this.state.condition
    }).then(res => {
      this.setState({ isLoading: false })
      if (res.status === 1) {
        const { disputeamount, casenum } = res.data
        this.setState({
          casenum: casenum || 0,
          disputeamount: disputeamount || 0
        })
      } else {
        this.setState({ isLoadError: true })
        message.warning(res.message)
      }
    }).catch(() => this.setState({ isLoading: false, isLoadError: true }))
  }

  // 二次弹框确认下载excel
  confirmDownload () {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要导出excel吗？',
      onOk: () => {
        this.downloadExcel()
      }
    })
  }

  // 下载excel
  downloadExcel () {
    json2Excel([
      this.formatSingleDataToExcel(this.state.chartOneData, '标的分布情况'),
      this.formatMultiDataToExcel(this.state.chartTwoData, '案由情况'),
      this.formatMultiDataToExcel(this.state.chartThreeData, '涉外涉港澳台案件情况'),
      // this.formatMultiDataToExcel(this.state.chartFourData, '外地案件情况'),
      this.formatMultiDataToExcel(this.state.chartFiveData, '结案方式'),
      this.formatMultiDataToExcel(this.state.chartSixData, '仲裁程序'),
      this.formatMultiDataToExcel(this.state.chartSevenData, '受理案件类型'),
      // this.formatMultiDataToExcel(this.state.chartSevenData, '案件类型'),
      {
        data: [{ 案件数: this.state.casenum, 总标的: this.state.disputeamount }],
        sheetname: '总数'
      }
    ], '案件统计')
  }

  // 格式化一行数据
  formatRowDataToExcel (data, type) {
    const map = {}
    if (type) {
      map['统计方式'] = type
    }
    data.list.forEach(li => {
      map[li.name] = li.value
    })
    if (data.total) {
      map['总数'] = data.total
    }
    return map
  }

  // 格式化单层数据为excel数据格式
  formatSingleDataToExcel (data, sheetname) {
    return {
      data: [this.formatRowDataToExcel(data)],
      sheetname
    }
  }

  // 格式化多层数据为excel数据格式
  formatMultiDataToExcel (data, sheetname) {
    return {
      data: [this.formatRowDataToExcel(data.casenum, '数量占比'), this.formatRowDataToExcel(data.disputeamount, '标的占比')],
      sheetname
    }
  }

  // 设置收案时间为当前年份
  getAcceptDateToCurrentYear () {
    const year = moment().year()
    const begin = moment(`${year}-01-01 00:00:00`)
    const end = moment(begin)
    end.add(1, 'y')
    end.subtract(1, 's')
    return {
      beginTime: begin,
      endTime: end
    }
  }

  // 改变表单
  changeForm (condition, formData) {
    this.setState({
      condition: JSON.stringify(condition),
      formData,
      searchVersion: Date.now(),
      type: formData.type
    }, () => {
      this.getTotalStatistic()
    })
  }

  componentDidUpdate (prev) {
    const m = prev.meta
    const tm = this.props.meta
    if (m !== tm) {
      this.initData()
    }
  }

  componentDidMount () {
    this.initData()
  }

  renderTotal () {
    const { isLoading, isLoadError, casenum, disputeamount } = this.state
    if (isLoading) {
      return <span className={style['top-right-total']}>获取数据中</span>
    }
    if (isLoadError) {
      return <span className={style['top-right-total']}>获取数据失败</span>
    }
    return (<span className={style['top-right-total']}>案件数 {casenum} 件 / 本请求总标的 {this.transferUnit(disputeamount)}</span>)
  }

  render () {
    const { formData, type } = this.state
    const initialValues = this.getAcceptDateToCurrentYear()
    return (
      <div className={style.container}>
        <SearchForm ref={this.formRef} name='my_case_manage' params={params} initialValues={initialValues} onChange={(condition, d) => this.changeForm(condition, d)} />
        <div className={style['total-line']}>
          <Button type='primary' ghost onClick={() => this.confirmDownload()} icon={<DownloadOutlined />}>导出excel</Button>
          <div className={style['total-info']}>{this.renderTotal()}</div>
        </div>
        <div className={style['block-half']}>
          <AcceptStatistic formData={formData} condition={this.state.condition} type={type} searchVersion={this.state.searchVersion} onChange={d => this.setState({ chartOneData: d })} />
        </div>
        <div className={style['block-half']}>
          <AcceptTypeStatistic formData={formData} condition={this.state.condition} type={type} searchVersion={this.state.searchVersion} onChange={d => this.setState({ chartSevenData: d })} />
        </div>
        {/* <div className={style['block-half']}>
          <FinanceStatistic formData={formData} condition={this.state.condition} type={type} searchVersion={this.state.searchVersion} onChange={d => this.setState({ chartTwoData: d })} />
        </div> */}
        <div className={style['block-half']}>
          <ForeignStatistic formData={formData} condition={this.state.condition} type={type} searchVersion={this.state.searchVersion} onChange={d => this.setState({ chartThreeData: d })} />
        </div>
        {/* <div className={style['block-half']}>
          <OtherPlaceStatistic formData={formData} condition={this.state.condition} type={type} searchVersion={this.state.searchVersion} onChange={d => this.setState({ chartFourData: d })} />
        </div> */}
        <div className={style['block-half']}>
          <ClosureStatistic formData={formData} condition={this.state.condition} type={type} searchVersion={this.state.searchVersion} onChange={d => this.setState({ chartFiveData: d })} />
        </div>
        <div className={style['block-half']}>
          <ProcedureStatistic formData={formData} condition={this.state.condition} type={type} searchVersion={this.state.searchVersion} onChange={d => this.setState({ chartSixData: d })} />
        </div>
        {/* <div className={style['block-half']}>
          <CaseTypeStatistic formData={formData} condition={this.state.condition} type={type} searchVersion={this.state.searchVersion} onChange={d => this.setState({ chartSevenData: d })} />
        </div> */}
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(CaseStatistic)
